package com.xian.jepathapp.util
import android.app.ActivityManager
import android.content.Context
import android.os.Build
import android.os.Environment
import android.os.StatFs
import java.io.PrintWriter
import java.io.StringWriter
import java.io.Writer
import java.text.SimpleDateFormat
import java.util.*

/**
 * 异常捕获
 */

object CrashHandler {

    fun init(){
        Thread.setDefaultUncaughtExceptionHandler(CaughtExceptionHandler())
    }

    private class  CaughtExceptionHandler : Thread.UncaughtExceptionHandler{
//        private val context= AppGlobals.get()!!
        private val formatter = SimpleDateFormat("yyyy-MM-dd-HH-mm-ss",Locale.CHINA)
        private var LAUNCH_TIME=formatter.format(Date())

        private var defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()

        override fun uncaughtException(t: Thread, e: Throwable) {
          if(handlerExcetion(e)&&defaultExceptionHandler!=null){
                 defaultExceptionHandler.uncaughtException(t,e)
          }
          restartApp()
        }
        private fun  handlerExcetion(e: Throwable):Boolean{
            if(e == null) return false
            val log=collectDeviceInfo(e)
//            if(BuildConfig.DEBUG){
//                //HiLog.e(log)
//            }
            saveCrashInfo2File(log)
            return true
        }

        private fun saveCrashInfo2File(log:String){
//            val crashDir=File(context.cacheDir,CRASH_DIR)
        }
        /**
         * 重启应用
         */
        private fun restartApp(){


        }
        /**
         * 设备类型、OS版本、线程名、前后台、使用时长、App版本、升级渠道
         * CPU架构、内存信息、存储信息、permission权限
         */
        private fun collectDeviceInfo(e:Throwable) : String{
            val sb = StringBuffer()
            sb.append("brand=${Build.BOARD}\n") //xiaomi,huawei
            sb.append("rom=${Build.MODEL}\n") //sm-G9550
            sb.append("os=${Build.VERSION.RELEASE}\n") //9.0
            sb.append("sdk=${Build.VERSION.SDK_INT}\n") //28
            sb.append("lauch_time=${LAUNCH_TIME}\n") //启动APP的时间
            sb.append("crash_time=${formatter.format(Date())}") //crash发生的时间
//            sb.append("forgroud=${ActivityManager.instance.front}\n") //应用处于前后台
            sb.append("thread=${Thread.currentThread().name}\n") //异常线程名
            sb.append("cpu_arch=${Build.CPU_ABI}\n") // armv7 armv8
            //app信息
//            val packageInfo = context.packageManger.getPackageInfo(context.packageName,0)
//            sb.append("version_code=${packgageInfo.versionCode}\n")
//            sb.append("version_name=${packgageInfo.versionName}\n")
//            sb.append("package_name=${packgageInfo.packageName}\n")
//            sb.append("requested_permission=${Arrays.toString(packageInfo.requestedPermissions)}\n") //已申请到的权限
            //统计一波 存储空间的信息
//            val memInfo = android.app.ActivityManager.MemoryInfo()
//            val ams=context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
//            ams.getMemoryInfo(memInfo)
//
//            sb.append("availMem=${android.text.format.Formatter.formatFileSize(context,memInfo.availMem)}\n") //可用内存
//            sb.append("totalMem=${android.text.format.Formatter.formatFileSize(context,memInfo.totalMem)}\n") //设备总内存
//            val file=Environment.getExternalStorageDirectory()
//            val statFs=StatFs(file.path)
//            val availableSize=statFs.availableBlocks*statFs.blockSize
//            sb.append("availStorage=${android.text.format.Formatter.formatFileSize(
//                context,availableSize.toLong())}\n") //存储空间

            val write: Writer =StringWriter()
            val printWriter = PrintWriter(write)
            e.printStackTrace(printWriter)
            var cause=e.cause
            while (cause!=null){
                cause.printStackTrace(printWriter)
                cause=cause.cause
            }
            printWriter.close()
            sb.append(write.toString())
            return  sb.toString()
        }
    }
}